package com.woniu108.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.json.JSONUtil;
import com.woniu108.gateway.config.AuthenticationUrlProperties;
import com.woniu108.gateway.exception.UserAuthenticaitonException;
import com.woniu108.gateway.model.Result;
import com.woniu108.gateway.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;
@Order(2)
@Component
public class AuthenticationFilter implements GlobalFilter {

    @Autowired
    private AuthenticationUrlProperties urls;

    private AntPathMatcher pm=new AntPathMatcher();


    /**
     * 判断当前url是否处于公共放行区间
     * @param url
     * @return
     */
    private boolean isBaseUrl(String url){
        if(urls.getBaseUrls()!=null&&urls.getBaseUrls().size()>0){
            for (String baseUrl : urls.getBaseUrls()) {
                if(pm.match(baseUrl,url)){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断当前url是否处于管理端url放行区间
     * @param url
     * @return
     */
    private boolean isSystemUrl(String url){
        if(urls.getSystemUrls()!=null&&urls.getSystemUrls().size()>0){
            for (String systemUrl : urls.getSystemUrls()) {
                if(pm.match(systemUrl,url)){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断当前url是否处于用户端url放行区间
     * @param url
     * @return
     */
    private boolean isUserUrl(String url){
        if(urls.getUserUrls()!=null&&urls.getUserUrls().size()>0){
            for (String userUrl : urls.getUserUrls()) {
                if(pm.match(userUrl,url)){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 响应未登录结果
     * @param exchange
     * @return
     */
    private Mono<Void> response(ServerWebExchange exchange){
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Result<String> result= Result.getResult(String.class).setMsg("未登录").setCode(401);
        String json= JSONUtil.parse(result).toString();
        return exchange.getResponse().writeWith(Mono.fromSupplier(()->{
            return exchange.getResponse().bufferFactory().wrap(json.getBytes());
        }));
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("=============登录验证=============");
        //判断权限:1.不需要权限(直接放行) 2.登录权限(有token即可访问) 3.管理员权限(api) 4. 用户权限(无后缀)
        String url=exchange.getRequest().getPath().toString();
        System.out.println("url:"+url);
        if(isBaseUrl(url)) return chain.filter(exchange);
        else {
            String token=null;
            List<String> headers=exchange.getRequest().getHeaders().get("token");
//            List<String> headers=exchange.getRequest().getHeaders().get("movie-token");
            if(headers!=null&&headers.size()>0) token=headers.get(0);
            //判断是什么系统的url
            if (url.endsWith(".c")){
                //通用功能后缀，有token即可访问
                if(token==null) throw new UserAuthenticaitonException("未登录",401);
                return chain.filter(exchange);
            }
            if(url.endsWith(".st")){
                if(token==null) throw new UserAuthenticaitonException("未登录",401);
                else{
                    //解析门店管理员token
                    try {
                        JWTUtil.parseStoreAdminToken(token);
                        return chain.filter(exchange);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new UserAuthenticaitonException("未登录",401);
                    }
                }
            }
            if (url.endsWith(".api")) {
                //管理员可用功能是否放行
                if (isSystemUrl(url)) return chain.filter(exchange);
                else {
                    if(token==null) throw new UserAuthenticaitonException("未登录",401);
                    else{
                        //解析管理员token
                        try {
                            JWTUtil.parseAdminToken(token);
                            return chain.filter(exchange);
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new UserAuthenticaitonException("未登录",401);
                        }
                    }
                }
            } else {
                //用户可用功能是否放行
                if (isUserUrl(url)) return chain.filter(exchange);
                else {
                    if(token==null) throw new UserAuthenticaitonException("未登录",401);
                    else{
                        //解析用户token
                        try {
                            JWTUtil.parseUserToken(token);
                            return chain.filter(exchange);
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new UserAuthenticaitonException("未登录",401);
                        }
                    }

                }
            }
        }
    }
}
